package org.anderground.editor;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.anderground.core.model.Station;
import org.anderground.core.util.Coord;

public class Test {
	public static final String API_KEY = "ABQIAAAAnPGuuUYw48AqcgDuMb2qzxTXnjCB_bLVAYR2HQb2zvWfgnaHEBSHyC766qz8snlmtJRBPJAbnM3I1A";

	public static Coord getStationCoord(Station station) {
		try {

			String request;
			String sity = "London";// EditorModel.getInstance().getData().getDescription().getCityName();
			request = sity.replaceAll(" ", "+") + ",+"
					+ station.getName().replaceAll(" ", "+");

			URL url = new URL("http://maps.google.com/maps/geo?q=" + request
					+ "&output=xml&key=" + API_KEY);

			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.addRequestProperty("REFERER",
					"http://androidmetro.googlepages.com/");

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			while(reader.ready()) {
				System.out.print(reader.readLine());
			}
			return getCoordFromGoogleXML(reader.readLine());

		} catch (MalformedURLException e) {
			return null;
			// e.printStackTrace();
		} catch (IOException e) {
			return null;
			// e.printStackTrace();
		}

	}

	private static Coord getCoordFromGoogleXML(String xml) {
		
		String strCoord;
		try {
			strCoord = xml.substring(xml.indexOf("<coordinates>")
					+ "<coordinates>".length(), xml.indexOf("</coordinates>"));
		} catch (java.lang.StringIndexOutOfBoundsException e) {
			return null;
		}
		String coords[] = strCoord.split(",");
		return new Coord(stringedFloatCoordToInt(coords[0]),
				stringedFloatCoordToInt(coords[1]));
	}

	private static int stringedFloatCoordToInt(String coord) {
		return (int) (Double.parseDouble(coord) * 1000000);
	}

}

